package com.zookeeper;

import org.apache.zookeeper.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class ZooKeeperNode {
    private final int SESSION_TIMEOUT=30000;
    // Create  ZooKeeper examples
    ZooKeeper zk;
    Watcher watcher = new Watcher() {
        public void process(WatchedEvent watchedEvent) {
            System.out.println(watchedEvent.toString());
        }
    };
    //Initialize ZooKeeper examples
    @Before
    public void before() throws IOException {
        zk = new ZooKeeper("192.168.200.200, 192.168.200.201, 192.168.200.202", SESSION_TIMEOUT, watcher);
    }
    @After
    public void after() throws InterruptedException {
        zk.close();
    }

    @Test
    public void create() throws KeeperException, InterruptedException {
        // When creating a node, you need to provide the name, data, permissions, and 	//node type of the node.
//        System.out.println("1.create ZooKeeper nodes (znode:zoo) 2,data:myData2,Permition:OPEN_ACL_UNSAFE,NodeType:Persistent)");
        System.out.println(" 1. 创建一个名为zk的节点，数据是myData,权限是完全开放");
        zk.create("/zk", "myData".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Test
    public void getData() throws KeeperException, InterruptedException {
//        System.out.println("2. Check to see if the creation was successful:");
        System.out.println(" 2. 获取节点信息-检查节点是否创建成功");
        System.out.println(new String(zk.getData("/zk", false, null)));
    }

    @Test
    public void setData() throws KeeperException, InterruptedException {
//        System.out.println("3. Modify node data:");
        System.out.println(" 3. 更新节点信息-修改节点数据");
        zk.setData("/zk", "xiugai".getBytes(), -1);
    }

    @Test
    public void getSetData() throws KeeperException, InterruptedException {
//        System.out.println("4. Check to see if the modify was successful:");
        System.out.println(" 4. 更新节点信息-检查是否修改成功");
        System.out.println(new String(zk.getData("/zk", false, null)));
    }

    @Test
    public void delete() throws InterruptedException, KeeperException {
//        System.err.println("5.delete nodes ");
        System.out.println(" 5. 删除节点");
        zk.delete("/zk", -1);
    }
}
